package com.hqd.ch03.v50.boot.autoconfigure.web.servlet;

import com.hqd.ch03.utils.ObjectUtils;
import com.hqd.ch03.v50.utils.StringUtils;

import javax.servlet.MultipartConfigElement;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

public class ServletRegistrationBean<T extends Servlet> extends DynamicRegistrationBean<ServletRegistration.Dynamic> {

    private static final String[] DEFAULT_MAPPINGS = {"/*"};

    private T servlet;

    private Set<String> urlMappings = new LinkedHashSet<>();

    private boolean alwaysMapUrl = true;

    private int loadOnStartup = -1;

    private MultipartConfigElement multipartConfig;

    /**
     * Create a new {@link ServletRegistrationBean} instance.
     */
    public ServletRegistrationBean() {
    }

    /**
     * Create a new {@link ServletRegistrationBean} instance with the specified
     * {@link Servlet} and URL mappings.
     *
     * @param servlet     the servlet being mapped
     * @param urlMappings the URLs being mapped
     */
    public ServletRegistrationBean(T servlet, String... urlMappings) {
        this(servlet, true, urlMappings);
    }

    /**
     * Create a new {@link ServletRegistrationBean} instance with the specified
     * {@link Servlet} and URL mappings.
     *
     * @param servlet      the servlet being mapped
     * @param alwaysMapUrl if omitted URL mappings should be replaced with '/*'
     * @param urlMappings  the URLs being mapped
     */
    public ServletRegistrationBean(T servlet, boolean alwaysMapUrl, String... urlMappings) {
        this.servlet = servlet;
        this.alwaysMapUrl = alwaysMapUrl;
        this.urlMappings.addAll(Arrays.asList(urlMappings));
    }

    /**
     * Return the servlet being registered.
     *
     * @return the servlet
     */
    public T getServlet() {
        return this.servlet;
    }

    /**
     * Sets the servlet to be registered.
     *
     * @param servlet the servlet
     */
    public void setServlet(T servlet) {
        this.servlet = servlet;
    }

    /**
     * Return a mutable collection of the URL mappings, as defined in the Servlet
     * specification, for the servlet.
     *
     * @return the urlMappings
     */
    public Collection<String> getUrlMappings() {
        return this.urlMappings;
    }

    /**
     * Set the URL mappings for the servlet. If not specified the mapping will default to
     * '/'. This will replace any previously specified mappings.
     *
     * @param urlMappings the mappings to set
     * @see #addUrlMappings(String...)
     */
    public void setUrlMappings(Collection<String> urlMappings) {
        this.urlMappings = new LinkedHashSet<>(urlMappings);
    }

    /**
     * Add URL mappings, as defined in the Servlet specification, for the servlet.
     *
     * @param urlMappings the mappings to add
     * @see #setUrlMappings(Collection)
     */
    public void addUrlMappings(String... urlMappings) {
        this.urlMappings.addAll(Arrays.asList(urlMappings));
    }

    /**
     * Sets the {@code loadOnStartup} priority. See
     * {@link ServletRegistration.Dynamic#setLoadOnStartup} for details.
     *
     * @param loadOnStartup if load on startup is enabled
     */
    public void setLoadOnStartup(int loadOnStartup) {
        this.loadOnStartup = loadOnStartup;
    }

    /**
     * Returns the {@link MultipartConfigElement multi-part configuration} to be applied
     * or {@code null}.
     *
     * @return the multipart config
     */
    public MultipartConfigElement getMultipartConfig() {
        return this.multipartConfig;
    }

    /**
     * Set the {@link MultipartConfigElement multi-part configuration}.
     *
     * @param multipartConfig the multipart configuration to set or {@code null}
     */
    public void setMultipartConfig(MultipartConfigElement multipartConfig) {
        this.multipartConfig = multipartConfig;
    }

    @Override
    protected String getDescription() {
        return "servlet " + getServletName();
    }

    @Override
    protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
        String name = getServletName();
        return servletContext.addServlet(name, this.servlet);
    }

    /**
     * Configure registration settings. Subclasses can override this method to perform
     * additional configuration if required.
     *
     * @param registration the registration
     */
    @Override
    protected void configure(ServletRegistration.Dynamic registration) {
        super.configure(registration);
        String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
        if (urlMapping.length == 0 && this.alwaysMapUrl) {
            urlMapping = DEFAULT_MAPPINGS;
        }
        if (!ObjectUtils.isEmpty(urlMapping)) {
            registration.addMapping(urlMapping);
        }
        registration.setLoadOnStartup(this.loadOnStartup);
        if (this.multipartConfig != null) {
            registration.setMultipartConfig(this.multipartConfig);
        }
    }

    /**
     * Returns the servlet name that will be registered.
     *
     * @return the servlet name
     */
    public String getServletName() {
        return getOrDeduceName(this.servlet);
    }

    @Override
    public String toString() {
        return getServletName() + " urls=" + getUrlMappings();
    }

}